package com.liukai.todo_android.common.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author ：liukai
 * @date ：Created in 2021/8/8 2:43 下午
 * @description：Retrofit的工具类
 * @modified By：
 * @version: $
 */
public class RetrofitManager {

    private static final RetrofitManager instance = new RetrofitManager(Constants.BASE_URL);
    private final Retrofit mRetrofit;

    public static RetrofitManager getInstance() {
        return instance;
    }

    private RetrofitManager(String BASEURL) {
        Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd HH:mm:ss")
                .serializeNulls()
                .create();
        // 创建Retrofit
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASEURL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(genericClient())
                .build();
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

    public static String date = "000000";

    public static OkHttpClient genericClient() {

        return new OkHttpClient.Builder()
                .addInterceptor(chain -> {
                    Request request = chain.request()
                            .newBuilder()
                            .addHeader("User-Agent", "xxxx/xxxx/" + date)
                            .addHeader(Constants.TOKEN_KEY, Constants.TOKEN)
                            .build();
                    return chain.proceed(request);
                }).connectTimeout(30, TimeUnit.SECONDS).
                        readTimeout(30, TimeUnit.SECONDS).
                        writeTimeout(30, TimeUnit.SECONDS).build();
    }

}
